package com.coupon.settlement.executor.impl;

import com.coupon.common.vo.CouponTemplateSDK;
import com.coupon.common.vo.SettlementInfo;
import com.coupon.settlement.constant.RuleFlagEnum;
import com.coupon.settlement.executor.AbstractExecutor;
import com.coupon.settlement.executor.RuleExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collections;

/**
 * @author 王哲
 * @Contact 1121586359@qq.com
 * @ClassName ManJianExecutor.java
 * @create 2023年06月27日 下午2:18
 * @Description 满减优惠卷规则执行器
 * @Version V1.0
 */
@Slf4j
@Component
public class ManJianExecutor extends AbstractExecutor implements RuleExecutor {
    /**
     * 规则类型标记
     *
     * @return {@link RuleFlagEnum}
     */
    @Override
    public RuleFlagEnum ruleConfig() {
        return RuleFlagEnum.MANJIAN;
    }

    /**
     * 优惠券规则计算
     *
     * @param settlement {@link SettlementInfo} 包含了选择的优惠券
     * @return {@link SettlementInfo} 修正过的结算信息
     */
    @Override
    public SettlementInfo computeRule(SettlementInfo settlement) {
        // 获取商品总价
        double goodsCost = retain2Decimals(goodsCostSum(settlement.getGoodsInfos()));

        SettlementInfo settlementInfo = processGoodsTypeNotSatisfy(settlement, goodsCost);

        if (settlementInfo!=null){
            log.debug("ManJian Template Is Not Match GoodsType!");
            return settlementInfo;
        }
        // 判断满减是否符合折扣标准
        CouponTemplateSDK templateSDK = settlement.getCouponAndTemplateInfos().get(0).getTemplateSDK();
        // 获取满减基准值
        double base = templateSDK.getRule().getDiscount().getBase();
        // 获取满减额度
        double quota = templateSDK.getRule().getDiscount().getQuota();

        // 如果不符合标准，则直接返回商品总价
        if (goodsCost<base){
            log.debug("Current Goods Cost Sum < ManJian Coupon Base!");
            settlement.setCost(goodsCost);
            settlement.setCouponAndTemplateInfos(Collections.emptyList());
            return settlement;
        }
        // 计算使用优惠券之后的价格 - 结算
        settlement.setCost(retain2Decimals(
                (goodsCost-quota)>minCost()?goodsCost-quota:minCost())
        );
        log.debug("Use ManJian Coupon Make Goods Cost From {} To {}",
                goodsCost,settlement.getCost());

        return settlement;
    }
}
